[Java] 使用DateTimeFormatterBuilder 解析日期字串


Posted by yaweichiang on 2022-11-26

在後端呼叫第三方API時取得的日期時間字串格式如下:/Date(xxxxxxxxxxxxx+xxxx)/
需要將日期時間字串轉換成以下格式:yyyy-MM-ddTHH:mm:ss

使用DateTimeFormatterBuilder建立符合原始字串的Formatter,用來將原始字串parse成相應LocalDateTime物件
再將LocalDateTime物件透過目標格式的Formatter格式化成我們所想要的日期時間格式字串

DateTimeFormatter jsonDateTimeFormatter = new DateTimeFormatterBuilder()
                .appendLiteral("/Date(")
                .appendValue(ChronoField.INSTANT_SECONDS)
                .appendValue(ChronoField.MILLI_OF_SECOND,3)
                .appendOffset("+HHmm","+0000")
                .appendLiteral(")/")
                .toFormatter();

DateTimeFormatter targetDateTimeFormatter = DateTiemFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
@JsonProperty("startDate")
private String startDate;

public void setStartDate(String startDate){
    if(startDate.matches("^\\/Date\\(\\d{13,13}\\+\\d{4,4}\\)\\/$")){
        LocalDatetime dateTime = LocalDateTime.parse(startDate,jsonDateTimeFormatter);
        startDate = dateTime.format(targetDateTimeFormatter);
    }
    this.startDate = startDate;
}

#java #DateTimeFormat #JsonDate







Related Posts

我的第一堂 - JavaScript 03 迴圈、函式

我的第一堂 - JavaScript 03 迴圈、函式

React 按下編輯按鈕後,想要自動 focus 在內容上

React 按下編輯按鈕後,想要自動 focus 在內容上

[ 筆記 ] 瀏覽器資料儲存 - Cookie、LocalStorage、SessionStorage

[ 筆記 ] 瀏覽器資料儲存 - Cookie、LocalStorage、SessionStorage


Comments